# 导入tushare
import tushare as ts
import pandas as pd
import time
from datetime import datetime, timedelta
# 初始化pro接口
pro = ts.pro_api('1c7f85b9026518588c0d0cdac712c2d17344332c9c8cfe6bc83ee75c')

def get_recent_stock_daily_data(days=15, pause=0.1):
    # 1. 获取最近的交易日列表
    def get_recent_trade_days(n):
        end_date = datetime.now().strftime('%Y%m%d')
        start_date = (datetime.now() - timedelta(days=n * 3)).strftime('%Y%m%d')  # 放宽日期范围

        cal = pro.trade_cal(exchange='', start_date=start_date, end_date=end_date)
        trade_days = cal[cal['is_open'] == 1]['cal_date'].tolist()
        return trade_days[-n:] if len(trade_days) >= n else trade_days

    trade_days = get_recent_trade_days(days)
    print(f"获取到最近{days}个交易日: {trade_days}")

    # 2. 获取当前所有上市股票列表
    stock_list = pro.stock_basic(exchange='', list_status='L')['ts_code'].tolist()
    print(f"共获取到{len(stock_list)}只股票")

    # 3. 获取日线数据
    all_data = pd.DataFrame()
    total_stocks = len(stock_list)

    for i, code in enumerate(stock_list):
        try:
            # 获取单只股票在多个交易日的日线数据
            df = pro.daily(ts_code=code, start_date=trade_days[-1], end_date=trade_days[0])
            all_data = pd.concat([all_data, df])

            # 显示进度
            if (i + 1) % 100 == 0 or (i + 1) == total_stocks:
                print(f"进度: {i + 1}/{total_stocks}，已获取{len(all_data)}条记录")

            time.sleep(pause)  # 避免频繁请求

        except Exception as e:
            print(f"获取{code}数据失败: {str(e)}")
            continue###

    # 4. 数据整理
    if not all_data.empty:
        # 转换日期格式
        all_data['trade_date'] = pd.to_datetime(all_data['trade_date'])

        # 按股票代码和交易日期排序
        all_data.sort_values(['ts_code', 'trade_date'], inplace=True)

        # 重置索引
        all_data.reset_index(drop=True, inplace=True)

        print(f"\n数据获取完成，共获取{len(all_data)}条记录")
        print(f"时间范围: {all_data['trade_date'].min()} 至 {all_data['trade_date'].max()}")
        print(f"包含股票数量: {all_data['ts_code'].nunique()}")
    else:
        print("未能获取任何数据")

    return all_data

stock_data = get_recent_stock_daily_data(days=15)
print(stock_data)